package com.unohacha.qqj.fzdr.main;

import android.content.SharedPreferences;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.unohacha.qqj.fzdr.R;
import com.unohacha.qqj.fzdr.adapter.BaseRVAdapter;
import com.unohacha.qqj.fzdr.adapter.BaseViewHolder;
import com.unohacha.qqj.fzdr.bean.Constants;
import com.unohacha.qqj.fzdr.bean.homebean.HomeOpenProvinceBean;
import com.unohacha.qqj.fzdr.imp.MyCallBack;
import com.unohacha.qqj.fzdr.imp.UrlConfig;
import com.unohacha.qqj.fzdr.imp.XUtil;
import com.unohacha.qqj.fzdr.util.BroadCastReceiverUtil;
import com.unohacha.qqj.fzdr.util.Prefer;
import com.unohacha.qqj.fzdr.util.ToastUtils;
import com.unohacha.qqj.mylibrary.base.BaseActivity;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 地区定位  直接是省，（中间跨过市） （市/区/线）
 */
public class RegionLocateActivity extends BaseActivity implements OnRefreshListener {

    @BindView(R.id.common_back)
    ImageView commonBack;
    @BindView(R.id.common_title)
    TextView commonTitle;
    @BindView(R.id.common_right_image)
    ImageView commonRightImage;
    @BindView(R.id.common_right_text)
    TextView commonRightText;
    @BindView(R.id.mRecyclerView)
    RecyclerView mRecyclerView;
    @BindView(R.id.mRefreshLayout)
    SmartRefreshLayout mRefreshLayout;

    private String address_id = "12685";//定位后的或者选择后的地址id ,默认先写余杭区
    private List<HomeOpenProvinceBean.DataEntity> openProList = new ArrayList<>();//开放城市的列表
    private BaseRVAdapter mBaseAdapter;
    Map<String, List<HomeOpenProvinceBean.DataEntity.CityEntity.ReaEntity>> reaMap = new HashMap<>();//所有省份的对应所有区域的集合，key = 省份name，value = 区域list
    List<HomeOpenProvinceBean.DataEntity.CityEntity.ReaEntity> reaListOfProvince;//对应省份的所有区域的集合
    private final int RESULT_LOCATION = 1001;//选择定位地址的

    SharedPreferences sharedPreferences;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_region_locate;
    }

    @Override
    protected void initView() {
        super.initView();
        sharedPreferences=getSharedPreferences("locationInfo",MODE_PRIVATE);
        commonTitle.setText(getResources().getString(R.string.title_region_location));
        commonRightImage.setVisibility(View.INVISIBLE);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayout.VERTICAL,false));
        mRefreshLayout.setOnRefreshListener(this);
        mRefreshLayout.setRefreshHeader(new ClassicsHeader(this));
        mRefreshLayout.setRefreshFooter(null);

        getOpenProvience();

    }

    @OnClick({R.id.common_back})
    public void onViewClicked(View view) {
        switch (view.getId()){
            case R.id.common_back://返回
                finish();
                break;
        }
    }


    @Override
    public void onRefresh(RefreshLayout refreshlayout) {
        refreshlayout.getLayout().postDelayed(new Runnable() {
            @Override
            public void run() {
                getOpenProvience();
            }
        },2000);
    }

    //获取开放城市
    private void getOpenProvience(){
        showLoading();
        XUtil.Post(UrlConfig.OPEN_PROVIENCE,new MyCallBack<String>(){
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                mRefreshLayout.finishRefresh();
                mRefreshLayout.resetNoMoreData();
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    if ("1".equals(jsonObject.optString("code"))){
                        Gson gson = new Gson();
                        HomeOpenProvinceBean provinceBean = gson.fromJson(result,HomeOpenProvinceBean.class);
                        if (null != provinceBean){
                            if (0 != openProList.size()){
                                openProList.clear();
                            }
                            openProList.addAll(provinceBean.getData());
                            for (int i = 0; i < provinceBean.getData().size(); i++) {
                                reaListOfProvince = new ArrayList<>();
                                List<HomeOpenProvinceBean.DataEntity.CityEntity> city = provinceBean.getData().get(i).getCity();
                                for (int j = 0; j < city.size(); j++) {
                                    List<HomeOpenProvinceBean.DataEntity.CityEntity.ReaEntity> rea = city.get(j).getRea();
                                    reaListOfProvince.addAll(rea);
                                }
                                reaMap.put(provinceBean.getData().get(i).getName(), reaListOfProvince);
                            }
                            setOpenRegionAdapter();
                        }
                    }else {
                        MyToast(jsonObject.optString("message"));
                    }
                    mRefreshLayout.finishLoadmore();
                    mRefreshLayout.finishLoadmoreWithNoMoreData();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFinished() {
                hideLoading();
                super.onFinished();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                hideLoading();
                super.onError(ex, isOnCallback);
            }
        });
    }

    private void setOpenRegionAdapter(){

        mBaseAdapter = new BaseRVAdapter(this,openProList) {
            @Override
            public int getLayoutId(int viewType) {
                return R.layout.item_region_location;
            }

            @Override
            public void onBind(BaseViewHolder holder, int position) {

                final int tagPosition = position;
                TextView title_one = holder.getTextView(R.id.title_one);

                RecyclerView item_recycler = holder.getView(R.id.item_recycler);
                item_recycler.setLayoutManager(new GridLayoutManager(RegionLocateActivity.this,
                        4,LinearLayout.VERTICAL,false));

                title_one.setText(openProList.get(position).getName());

                final List<HomeOpenProvinceBean.DataEntity.CityEntity.ReaEntity> reaEntities = reaMap.get(openProList.get(position).getName());

                BaseRVAdapter itemBaseAdapter = new BaseRVAdapter(RegionLocateActivity.this,reaEntities) {
                    @Override
                    public int getLayoutId(int viewType) {
                        return R.layout.item_region_location_text;
                    }

                    @Override
                    public void onBind(BaseViewHolder holder, final int position) {
                        TextView item_region_tv = holder.getTextView(R.id.item_region_tv);
                        item_region_tv.setText(reaEntities.get(position).getName());
                        
                        item_region_tv.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                Prefer.getInstance().saveAreaId(RegionLocateActivity.this,reaEntities.get(position).getId()+"");
                                SharedPreferences.Editor editor=sharedPreferences.edit();
                                editor.putInt("city_id", openProList.get(tagPosition).getId());
                                editor.commit();
//                                MyToast("" + reaEntities.get(position).getName() +
//                                        " : " + reaEntities.size() + ":" +
//                                       openProList.get(tagPosition).getName());

                                BroadCastReceiverUtil.sendBroadcast(RegionLocateActivity.this,Constants.ACTION_UPTATE_LOCATION,
                                        "address_id",reaEntities.get(position).getId()+"",
                                             "name",reaEntities.get(position).getName());
                                finish();
                            }
                        });
                    }

                };
                item_recycler.setAdapter(itemBaseAdapter);
            }

        };
        mRecyclerView.setAdapter(mBaseAdapter);
        mBaseAdapter.notifyDataSetChanged();
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();

    }

}
